package com.kbbywyclient.ui.activity;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;

import com.kbbywyclient.R;
import com.kbbywyclient.app.App;
import com.kbbywyclient.app.Constants;
import com.kbbywyclient.app.Key;
import com.kbbywyclient.callback.WeChatPayCallback;
import com.kbbywyclient.data.entity.UnionPayInfo;
import com.kbbywyclient.data.entity.WeChatPayParams;
import com.kbbywyclient.di.AppComponent;
import com.kbbywyclient.di.module.RechargeModule;
import com.kbbywyclient.presenter.RechargePresenter;
import com.kbbywyclient.ui.activity.base.BaseActivity;
import com.kbbywyclient.ui.contarct.RechargeContract;
import com.kbbywyclient.util.ActivitySkipUtil;
import com.kbbywyclient.util.LogUtil;
import com.kbbywyclient.util.MD5Utils;
import com.kbbywyclient.util.SoftKeyboardUtils;
import com.kbbywyclient.util.StringUtil;
import com.kbbywyclient.util.ToastUtil;
import com.kbbywyclient.util.pre.PreUtils;
import com.kbbywyclient.widget.CustomDialog;
import com.kbbywyclient.widget.CustomToolBar;
import com.tencent.mm.opensdk.modelpay.PayReq;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;
import com.unionpay.UPPayAssistEx;

import java.util.HashMap;

import javax.inject.Inject;

import butterknife.BindView;
import butterknife.OnClick;
import butterknife.OnFocusChange;

/**
 * Created by cbb on 2017/4/17.
 */

public class RechargeActivity extends BaseActivity implements RechargeContract.View, WeChatPayCallback {
    @BindView(R.id.v_toolbar)
    CustomToolBar v_toolbar;
    @BindView(R.id.rg_choose_amount)
    RadioGroup rg_choose_amount;
    @BindView(R.id.et_recharge_amount)
    EditText et_recharge_amount;
    @BindView(R.id.rl_we_chat_pay)
    RelativeLayout rl_we_chat_pay;
    @BindView(R.id.cb_we_chat_pay)
    CheckBox cb_we_chat_pay;
    @BindView(R.id.rl_union_pay)
    RelativeLayout rl_union_pay;
    @BindView(R.id.cb_union_pay)
    CheckBox cb_union_pay;
    @BindView(R.id.bt_ensure_pay)
    Button bt_ensure_pay;

    @Inject
    RechargePresenter rechargePresenter;

    private CustomDialog enSurePaymentDialog;

    private int chargeAmount = 0;//充值金额，目前仅支持充值整数金额，[300,2000]

    private String CompanyID = "";
    private String CompanyTypeID = "";

    private IWXAPI iwxapi;

    @Override
    protected int provideContentViewId() {
        return R.layout.activity_recharge;
    }

    @Override
    protected void onResume() {
        super.onResume();
        setScreenName("充值");
    }

    @Override
    protected void initView() {
        iwxapi = WXAPIFactory.createWXAPI(this, Key.weChatAppId);
        App.getInstance().weChatPayCallback = this;
        v_toolbar.setLeftViewOnClickLinster(v -> finish());
        // TODO: 2017/4/17
        v_toolbar.setRightViewOnClickLinster(v -> finish());

        rg_choose_amount.setOnCheckedChangeListener((group, checkedId) -> {
            if (group.getCheckedRadioButtonId() != -1) {
                //清除输入框焦点
                et_recharge_amount.clearFocus();
                SoftKeyboardUtils.hideSoftKeyboard(rg_choose_amount);
                switch (checkedId) {
                    case R.id.rb_amount_300:
                        //300元
                        chargeAmount = 300;
                        break;
                    case R.id.rb_amount_500:
                        //500元
                        chargeAmount = 500;
                        break;
                    case R.id.rb_amount_800:
                        //800元
                        chargeAmount = 800;
                        break;
                }
            }
        });
    }

    @Override
    public void initData() {
        Intent intent = getIntent();
        CompanyID = intent.getStringExtra("CompanyID");
        CompanyTypeID = intent.getStringExtra("CompanyTypeID");
    }

    @Override
    public void initAppComponent(AppComponent appComponent) {
        appComponent.getRechargeComponent(new RechargeModule(this)).inject(this);
    }

    @OnFocusChange(R.id.et_recharge_amount)
    void onFocusChange(View view, boolean hasFocus) {
        if (hasFocus) {
            //清空radioGroup选中状态
            rg_choose_amount.clearCheck();
            rg_choose_amount.clearFocus();
            SoftKeyboardUtils.showSoftKeyboard(et_recharge_amount);
            //重置充值金额
            chargeAmount = 0;
            //设置充值输入框光标位置
            String amount = et_recharge_amount.getEditableText().toString().trim();
            if (amount.length() > 0) {
                et_recharge_amount.setSelection(amount.length());
            }
            //改变输入框背景
            et_recharge_amount.setBackgroundResource(R.drawable.shape_stroke_14c095_corners_5_solid_ff);
        } else {
            //清除充值输入框内容，重新设置背景
            et_recharge_amount.setText("");
            et_recharge_amount.setBackgroundResource(R.drawable.shape_stroke_dd_corners_5_solid_ff);
        }
    }


    @OnClick({R.id.rl_we_chat_pay, R.id.rl_union_pay, R.id.bt_ensure_pay})
    void onClick(View v) {
        switch (v.getId()) {
            case R.id.rl_we_chat_pay:
                cb_we_chat_pay.setChecked(true);
                cb_union_pay.setChecked(false);
                break;
            case R.id.rl_union_pay:
                cb_we_chat_pay.setChecked(false);
                cb_union_pay.setChecked(true);
                break;
            case R.id.bt_ensure_pay:
                if (rg_choose_amount.getCheckedRadioButtonId() == -1) {
                    if (checkRechargeAmountValidity()) {
                        showPaymentEnsureDialog();
                    }
                } else {
                    if (cb_we_chat_pay.isChecked()) {
                        //微信支付时，判断下微信支付是否可用
                        if (!iwxapi.isWXAppInstalled()) {
                            ToastUtil.showLong("请安装微信后再使用此功能");
                            return;
                        }
                        showPaymentEnsureDialog();
                    } else {
                        showPaymentEnsureDialog();
                    }
                }
                break;
        }
    }

    //检查输入的充值金额合法性
    private boolean checkRechargeAmountValidity() {
        String errorMsg = "";
        boolean flag = false;
        try {
            String amountStr = et_recharge_amount.getText().toString().trim();
            if (StringUtil.isEmpty(amountStr)) {
                errorMsg = "请选择或者输入充值金额";
            } else {
                int amount = Integer.parseInt(amountStr);
                if (amount >= 300 && amount <= 2000) {
                    this.chargeAmount = amount;
                    flag = true;
                } else {
                    errorMsg = "充值金额只能在300-2000之间";
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            errorMsg = "输入错误，非法的数字";
        }
        if (!TextUtils.isEmpty(errorMsg)) {
            ToastUtil.showLong(errorMsg);
        }
        return flag;
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (data != null) {
            String msg = data.getExtras().getString("pay_result");
            if ("success".equalsIgnoreCase(msg)) {
                toReChargeSuccessActivity();
            } else if ("failure".equalsIgnoreCase(msg)) {
                LogUtil.d("支付失败");
                toRechargeFailureActivity();
            } else if ("cancel".equalsIgnoreCase(msg)) {
                handlePayCancel();
            }
        }
    }


    @Override
    public void onDestroy() {
        //将application中持有的此activity引用释放掉
        App.getInstance().weChatPayCallback = null;
        super.onDestroy();
    }

    @Override
    public void showLoadingDialog(String s) {
        showProgress(s);
    }

    @Override
    public void closeLoadingDialog() {
        dismissProgress();
    }

    CustomDialog.ButtonListener listener = new CustomDialog.ButtonListener() {
        @Override
        public void left() {
            dismissPaymentEnsureDialog();
        }

        @Override
        public void right() {
            dismissPaymentEnsureDialog();
            Context context = RechargeActivity.this;
            if (cb_we_chat_pay.isChecked()) {
                setScreenAction("充值", "微信支付");
                //微信支付
                rechargePresenter.getWeChatPayInfo(String.valueOf(PreUtils.getUser(context).getSalesID()),
                        MD5Utils.md5(StringUtil.getDeviceId(context)),
                        "1",
                        String.valueOf(chargeAmount));
            } else if (cb_union_pay.isChecked()) {
                setScreenAction("充值", "银联支付");
                //银联支付
                rechargePresenter.getUnionPayInfo(String.valueOf(PreUtils.getUser(context).getSalesID()),
                        MD5Utils.md5(StringUtil.getDeviceId(context)),
                        "1",
                        String.valueOf(chargeAmount));
            }
        }
    };

    private void showPaymentEnsureDialog() {
        if (null == enSurePaymentDialog) {
            enSurePaymentDialog = new CustomDialog(this, R.style.Customdialog, "确认充值金额", "", listener, "返回修改", "确定充值");
        }
        enSurePaymentDialog.setContent("您将充值" + chargeAmount + "元到您的账号上，确定充值？");
        enSurePaymentDialog.show();
    }

    private void dismissPaymentEnsureDialog() {
        if (null != enSurePaymentDialog) {
            enSurePaymentDialog.dismiss();
        }
    }

    @Override
    public void onGetWeChatPayInfoSuccess(WeChatPayParams weChatPayParams) {
        if ("1".equals(weChatPayParams.getStatus())) {
            //成功，唤起微信支付
            final PayReq payReq = new PayReq();
            payReq.appId = weChatPayParams.getAppId();
            payReq.partnerId = weChatPayParams.getPartnerId();
            payReq.prepayId = weChatPayParams.getPrepayId();
            payReq.nonceStr = weChatPayParams.getNonceStr();
            payReq.timeStamp = weChatPayParams.getTimeStamp();
            payReq.packageValue = weChatPayParams.getPackageValue();
            payReq.sign = weChatPayParams.getSign();
            payReq.extData = getClass().getName();
            boolean call = iwxapi.sendReq(payReq);
            LogUtil.d("调用微信支付结果:" + call);
        } else {
            //失败
            ToastUtil.showLong(weChatPayParams.getMsg());
        }
    }


    @Override
    public void onGetUnionPayInfoSuccess(UnionPayInfo unionPayInfo) {
        String msg = unionPayInfo.getMsg();
        if ("1".equals(unionPayInfo.getStatus())) {
            //正式环境00 测试环境01
            int code = UPPayAssistEx.startPay(this, null, null, msg, "00");
        } else {
            if (!TextUtils.isEmpty(msg)) {
                ToastUtil.showLong(msg);
            }
        }
    }

    //去往支付成功后的页面
    private void toReChargeSuccessActivity() {
        HashMap<String, Object> map = new HashMap<>();
        map.put("chargeAmount", chargeAmount);
        map.put("CompanyID", CompanyID);
        map.put("CompanyTypeID", CompanyTypeID);
        ActivitySkipUtil.skipAnotherActivity(this, RechargeSuccessActivity.class, map);
        finish();
    }

    //去往支付失败后的页面
    private void toRechargeFailureActivity() {
        HashMap<String, Object> map = new HashMap<>();
        map.put("chargeAmount", chargeAmount);
        map.put("payType", cb_we_chat_pay.isChecked() ? Constants.PAY_TYPE_WE_CHAT : Constants.PAY_TYPE_UNION);
        ActivitySkipUtil.skipAnotherActivity(this, RechargeFailureActivity.class, map);
        finish();
    }

    //处理支付取消，暂时只显示Toast，提醒用户支付取消
    private void handlePayCancel() {
        ToastUtil.showShort("您取消了支付");
    }

    @Override
    public void onWeChatPaySuccess() {
        //支付成功，跳转到支付成功页面
        toReChargeSuccessActivity();
    }

    @Override
    public void onWeChatPayFailure() {
        //支付失败，跳转到充值失败页面
        toRechargeFailureActivity();
    }

    @Override
    public void onWeChatPayCancel() {
        handlePayCancel();
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putInt("chargeAmount", chargeAmount);
        outState.putString("CompanyID", CompanyID);
        outState.putString("CompanyTypeID", CompanyTypeID);
    }

    @Override
    protected void onRestoreInstanceState(Bundle savedInstanceState) {
        super.onRestoreInstanceState(savedInstanceState);
        chargeAmount = savedInstanceState.getInt("chargeAmount");
        CompanyID = savedInstanceState.getString("CompanyID");
        CompanyTypeID = savedInstanceState.getString("CompanyTypeID");
    }
}
